﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IGIS.Core;
using System.IO;
using WebUI.Controls;
using System.Drawing;
using System.Data;

namespace IGIS.Controls
{
    public partial class FeatureEditorControl : System.Web.UI.UserControl
    {
         private bool _activated;
        private Feature _feature;
        protected DetailsView _FeatureCard;
        private HtzMgHelper _helper;
        //protected ScriptManagerProxy scriptManagerProxy;
        //protected Panel SdfEditorPanel;
        //protected HiddenField SdfFileName;

        public event EventHandler<ErrorEventArgs> ControlError;

        public event EventHandler RefreshRequired;

        protected void _FeatureCard_DataBound(object sender, EventArgs e)
        {
            if (this._feature != null)
            {
                this._FeatureCard.DataSource = this._feature.FeatureDataSet;
                foreach (KeyValuePair<string, FeatureProperty> p in this._feature.Properties)
                {
                    int val;
                    Control c = this._FeatureCard.FindControl(p.Key);
                    if (c != null)
                    {
                        if (c.GetType() == typeof(TextBox))
                        {
                            TextBox tb = (TextBox) c;
                            tb.Text = DataBinder.Eval(this._FeatureCard.DataItem, p.Key, "{0}");
                            if ((p.Value.PropertyType == 3) && tb.Text.StartsWith("01/01/0001"))
                            {
                                tb.Text = string.Empty;
                            }
                        }
                        else if (c.GetType() == typeof(Label))
                        {
                            Label lbl = (Label) c;
                            if (p.Value.Value != null)
                            {
                                lbl.Text = p.Value.DisplayedValue;
                            }
                        }
                        else if (c.GetType() == typeof(CheckBox))
                        {
                            CheckBox cb = (CheckBox) c;
                            cb.Checked = bool.Parse(p.Value.Value.ToString());
                            Label lbl1 = (Label) this._FeatureCard.FindControl("lbl_" + p.Key);
                            if (lbl1 != null)
                            {
                                lbl1.Text = cb.Checked ? "(כן)" : "(לא)";
                            }
                        }
                        Control c_txt = this._FeatureCard.FindControl(p.Key + "_txt");
                        if (c_txt != null)
                        {
                            val = Convert.ToInt32(p.Value.Value);
                            IEnumerable<KeyValuePair<int, string>> vals = from x in p.Value.LookUpValues
                                where x.Key == val
                                select x;
                            foreach (KeyValuePair<int, string> v in vals)
                            {
                                Label lblTxt = (Label) c_txt;
                                lblTxt.Text = v.Value;
                                break;
                            }
                        }
                    }
                }
            }
        }

        protected void _FeatureCard_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
        {
            DetailsView dv = (DetailsView) sender;
            DataRow r = ((DataRowView) dv.DataItem).Row;
            if (!e.Cancel)
            {
                for (int i = 0; i < dv.Rows.Count; i++)
                {
                    for (int j = 0; j < dv.Rows[i].Cells.Count; j++)
                    {
                        for (int k = 0; k < dv.Rows[i].Cells[j].Controls.Count; k++)
                        {
                            Control control = dv.Rows[i].Cells[j].Controls[k];
                            if (control.GetType() == typeof(TextBox))
                            {
                                TextBox tb = (TextBox) control;
                                this._feature.Properties[tb.ID].Value = tb.Text;
                                r[tb.ID] = tb.Text;
                            }
                            else if (control.GetType() == typeof(DropDownList))
                            {
                                DropDownList ddl = (DropDownList) control;
                                this._feature.Properties[ddl.ID].Value = ddl.SelectedValue;
                                r[ddl.ID] = ddl.SelectedItem;
                            }
                            else if (control.GetType() == typeof(CheckBox))
                            {
                                CheckBox cb = (CheckBox) control;
                                this._feature.Properties[cb.ID].Value = cb.Checked;
                                r[cb.ID] = cb.Checked;
                            }
                        }
                    }
                }
            }
            this._feature.UpdateFeature(this.Filter);
            dv.ChangeMode(DetailsViewMode.ReadOnly);
            dv.DataBind();
            this.ForceRefresh();
        }

        protected void _FeatureView_ModeChanging(object sender, DetailsViewModeEventArgs e)
        {
            DetailsView dv = (DetailsView) sender;
            dv.ChangeMode(e.NewMode);
            dv.DataBind();
        }

        public void Activate(HtzMgHelper helper, Feature feature)
        {
            this._helper = helper;
            this._feature = feature;
            this._activated = true;
        }

        public void FeatureCard_Init()
        {
            try
            {
                if (!string.IsNullOrEmpty(this._helper.GetSdfFile(this._feature.Layer.GetFeatureSourceId())))
                {
                    this.SdfFileName.Value = this._helper.GetSdfFile(this._feature.Layer.GetFeatureSourceId());
                    this.SdfEditorPanel.Visible = true;
                }
                this._FeatureCard.Fields.Clear();
                foreach (KeyValuePair<string, FeatureProperty> p in from x in this._feature.Properties
                    orderby x.Value.OrderId, x.Value.Alias
                    select x)
                {
                    TemplateField myTemplate = new TemplateField {
                        EditItemTemplate = new EditPropertyFieldTemplate(p.Value, this.SdfFileName.Value),
                        ItemTemplate = new ViewPropertyFieldTemplate(p.Value),
                        HeaderText = p.Value.Alias
                    };
                    
                    this._FeatureCard.Fields.Add(myTemplate);
                }
                TemplateField myFooterTemplate = new TemplateField();
                ViewFooterTemplate viewFooter = new ViewFooterTemplate();
                EditFooterTemplate editFooter = new EditFooterTemplate();
                myFooterTemplate.ItemTemplate = viewFooter;
                myFooterTemplate.EditItemTemplate = editFooter;
                myFooterTemplate.ShowHeader = false;
                myFooterTemplate.ItemStyle.BackColor = Color.FromArgb(0xff, 0xff, 0xc0);
                this._FeatureCard.Fields.Add(myFooterTemplate);
                this._FeatureCard.Fields.Insert(0, myFooterTemplate);
                this._FeatureCard.AutoGenerateRows = false;
                this._FeatureCard.DataSource = this._feature.FeatureDataSet;
                this._FeatureCard.DataBind();
            }
            catch (InvalidOperationException ex)
            {
                this.ControlError(this, new ErrorEventArgs(ex));
            }
        }

        private void ForceRefresh()
        {
            if (this.RefreshRequired != null)
            {
                this.RefreshRequired(this, EventArgs.Empty);
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this._FeatureCard.ModeChanging += new DetailsViewModeEventHandler(this._FeatureView_ModeChanging);
            this._FeatureCard.ItemUpdating += new DetailsViewUpdateEventHandler(this._FeatureCard_ItemUpdating);
            this._FeatureCard.DataBound += new EventHandler(this._FeatureCard_DataBound);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            _activated = true;
            if (this._activated && (this._helper != null))
            {
                this.FeatureCard_Init();
            }
        }

        public bool EditMode
        {
            get
            {
                return (this._FeatureCard.CurrentMode != DetailsViewMode.ReadOnly);
            }
            set
            {
                if (!value)
                {
                    this._FeatureCard.ChangeMode(DetailsViewMode.ReadOnly);
                }
            }
        }

        public string Filter { get; set; }

        public string LayerLegend { get; set; }
    }
    }
